<template>
    <!-- <h1>i m user</h1> -->
    <div class="manage">
        <!-- 新增弹窗 -->
        <el-dialog
        :title="dialogtitle"
        :visible.sync="dialogVisible" 
        :before-close="handleClose"
        width="50%">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px" :inline="true" >
            <el-form-item label="用户名" prop="nickName">
                <el-input placeholder="请输入用户名" v-model="form.nickName"></el-input>
            </el-form-item>

            <el-form-item label="年级" prop="grade">
                <el-select v-model="form.grade" placeholder="请选择年级">
                    <el-option label="2015" value="2015"></el-option>
                    <el-option label="2016" value="2016"></el-option>
                    <el-option label="2017" value="2017"></el-option>
                    <el-option label="2018" value="2018"></el-option>
                    <el-option label="2019" value="2019"></el-option>
                    <el-option label="2020" value="2020"></el-option>
                    <el-option label="2021" value="2021"></el-option>
                    <el-option label="2022" value="2022"></el-option>
                    <el-option label="2023" value="2023"></el-option>
                    <el-option label="2024" value="2024"></el-option>
                    <el-option label="2025" value="2025"></el-option>
                    <el-option label="2026" value="2026"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="学院" prop="college">
                <el-select v-model="form.college" placeholder="请选择学院">
                    <el-option label="信息与通信工程学院" value="信息与通信工程学院"></el-option>
                    <el-option label="电子工程学院" value="电子工程学院"></el-option>
                    <el-option label="计算机学院（国家示范性软件学院）" value="计算机学院（国家示范性软件学院）"></el-option>
                    <el-option label="网络空间安全学院" value="网络空间安全学院"></el-option>
                    <el-option label="人工智能学院" value="人工智能学院"></el-option>
                    <el-option label="现代邮政学院（自动化学院）" value="现代邮政学院（自动化学院）"></el-option>
                    <el-option label="集成电路学院" value="集成电路学院"></el-option>
                    <el-option label="经济管理学院" value="经济管理学院"></el-option>
                    <el-option label="人文学院" value="人文学院"></el-option>
                    <el-option label="国际学院" value="国际学院"></el-option>
                    <el-option label="马克思主义学院" value="马克思主义学院"></el-option>
                    <el-option label="网络教育学院（继续教育学院）" value="网络教育学院（继续教育学院）"></el-option>
                    <el-option label="理学院" value="理学院"></el-option>
                    <el-option label="数字媒体与设计艺术学院" value="数字媒体与设计艺术学院"></el-option>
                    <el-option label="应急管理学院" value="应急管理学院"></el-option>
                    <el-option label="体育部" value="体育部"></el-option>
                    <el-option label="其他" value="其他"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="专业" prop="major">
                <el-input placeholder="请输入专业" v-model="form.major"></el-input>
            </el-form-item>

        </el-form>
            
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
        </span>
        </el-dialog>

        <!-- +新增按钮 -->
        <!-- <div class="manage-header">
            <el-button @click="handleAdd" type="primary">
                + 新增
            </el-button>
        </div> -->

        <div class="common-table">
        <el-table
        height="90%"
        :data="usersInfo"
        stripe
        :row-style="{height: '100px'}"
        style="width: 100%">
            <el-table-column
                prop="_openid"
                label="openID">
            </el-table-column>
            <el-table-column
                prop="nickName"
                label="用户名">
            </el-table-column>
            <el-table-column
                prop="grade"
                label="年级">
            </el-table-column>
            <el-table-column
                prop="college"
                label="学院">
            </el-table-column>
            <el-table-column
                prop="major"
                label="专业">
            </el-table-column>
            <el-table-column
                prop="getNum"
                label="获取书籍数量">
            </el-table-column>
            <el-table-column
                prop="getNum"
                label="捐赠书籍数量">
            </el-table-column>
            <el-table-column
                prop="operation"
                label="操作">
                <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pager">
            <el-pagination
                layout="prev, pager, next"
                :total="this.total"
                @current-change="handlePage">
            </el-pagination>
        </div>
    </div>
    </div>
</template>

<script>

export default{
    name:'User',
    data(){
        return{
            usersInfo:[],
            db:'',
            //Info中总条数
            total:0,
            pageData:{
                pageSize: 10,
                currentPage : 1
            },
            dialogVisible:false,
            dialogtitle:"新增用户",
            //tableData中总条数
            total:0,
            obj:'',
            //空form解决回显bug
            empty_form:{
                nickName:'',
                grade:'',
                college:'',
                major:'',
            },
            // 需要显示的数据
            form:{
                nickName:'',
                grade:'',
                college:'',
                major:'',
            },
            rules:{
                nickName:[
                    {required:true , message:'请输入用户名'}
                ],          
                college:[
                    {required:true , message:'请选择学院'}
                ],
                major:[
                    {required:true , message:'请输入专业'}
                ],
                grade:[
                    {required:true , message:'请选择年级'}
                ],

            },
            modaltype:0//0新增，1编辑，标记弹窗状态
        }
    },
    methods:{
        initdb(){
            let that = this
            var c1 = new that.$cloud.Cloud({
                 //必填，表示是未登录模式
                identityless: true,
                //资源方 AppID
                resourceAppid: 'wx3a07f3c2fa333336',
                //资源方环境 ID
                resourceEnv: 'ayaka557-2gh3t7jm380b9701',
            })
            c1.init()
            // console.log('c1',c1);
            //获取云数据库信息
            this.db = c1.database();
            // console.log('db',this.db)
        },
        getWxUsers(){
            //封装一下分页查询
            this.getUsersData(this.pageData.pageSize,this.pageData.currentPage)
        },
        getUsersData(pageSize,currentPage){
            // 分页查询数据
            this.db.collection('users').skip(pageSize*(currentPage - 1)).limit(pageSize).get()
                .then(res => {
                    this.usersInfo = res.data
                    console.log('users', this.usersInfo)
                    this.db.collection('users').count()
                        .then(res => {
                            console.log('total',res);
                            this.total = res.total
                        })
                        .catch(err => {
                            console.log('err',err);
                            
                        })
                    console.log('count',this.total);
                    
                })
                .catch(err => {
                    console.log(err);
                });
        },
        handleAdd(){
            //显示调用去掉bug
            // this.handleClose()
            //修改弹窗状态
            this.modaltype = 0//新增
            this.dialogtitle = "新增用户"
            //显示弹窗
            this.dialogVisible = true
        },
        handleClose(){
            this.$refs.form.resetFields()
            console.log("关闭弹窗，reset success")
            console.log("关闭后表单",this.form)
            this.dialogVisible = false
        },
        handleEdit(row){
            console.log("当前准备进行修改的行数据",row)
            //先修改弹窗的模式与标题，再显示弹窗
            this.modaltype = 1
            this.dialogtitle = " 修改用户信息"
            this.dialogVisible = true

            //不能直接赋值，不然直接修改了数据，需要点击确认才能修改
            //利用obj存储row中冗余的id项以及其余可能项，并传入obj的row进行修改
            //不使用this.obj =  row是因为这样两个变量会指向同一块地址，实际上是同一个变量的两个引用
            //回显
            this.tempObj = JSON.parse(JSON.stringify(row));
            this.form = {
                nickName:this.tempObj.nickName,
                grade:this.tempObj.grade,
                college:this.tempObj.college,
                major:this.tempObj.major
            }

        },
        handleDelete(row){
            console.log("deleteRowId",row._id)
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {//用户点击了确认按钮
                console.log('我要删除');
                this.db.collection('users').doc(row._id).remove()
                .then(() => {
                    console.log('User deleted successfully');

                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                        });
                    // 更新通知列表
                    this.getWxUsers();
                })
                .catch(err => {
                    console.error('Error deleting user: ', err)
                    this.$message({
                        type: 'info',
                        message: '未知原因删除失败'
                    });       
                });

            }).catch(() => {//用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        submit(){
            this.$refs.form.validate((valid) => {
                //如果数据不完整，valid为false
                if(valid){
                    console.log(this.form);
                    //this.form是data,this.$refs.form是真正的表单
                    if(this.modaltype === 0){
                    //不允许新增
                    //    //对后端发送增加请求......
                    //     this.add_time_form.name = this.form.name
                    //     this.add_time_form.detail = this.form.detail
                    //     this.add_time_form.time = new Date()
                    //     console.log('addForm',this.add_time_form)
                    //     this.db.collection('notices').add({data:this.add_time_form})  
                    //         .then(() => {
                    //             console.log('Notice added successfully');
                    //             // 更新通知列表
                    //             this.getWxNotices()
                    //         })
                    //         .catch(err => {
                    //             console.error('Error adding notice: ', err);
                    //         });  
                    }else{//修改
                        //对后端修改增加请求......
                        this.db.collection('users').doc(this.tempObj._id).update({data:this.form})
                            .then(() => {
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                    });
                                // 更新通知列表
                                this.getWxUsers();
                            })
                            .catch(err => {
                                console.error('Error deleting notice: ', err)
                                this.$message({
                                    type: 'info',
                                    message: '未知原因修改失败'
                                });       
                            });
                    }
                    this.handleClose()
                }
                else{
                    //do nothing
                }
            })
        },
        cancel(){
            this.handleClose()
        },
        handlePage(currentPage){
            //当点击分页栏的时候，传入页面号
            console.log(currentPage)
            this.pageData.currentPage = currentPage
            this.getWxUsers()
        }



    },    
    mounted(){
        this.initdb()
        this.getWxUsers()
    }
}
</script>

<style lang="less">
.manage{
    height: 100%;
    .common-table{
        position: relative;
        height: calc(100% - 62px);
        .pager{
        position: absolute;
        bottom: 0;
        right: 20px;
        }
    }
    
}
</style>